<?php

namespace App\Admin\Controllers;

use App\Admin\Grid\Tools\ImportUserToolButton;
use App\Admin\Metrics\Examples\MyCard;
use App\Models\Administrator;
use App\Models\Department;
use App\Models\UserGroup;
use Carbon\Carbon;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Metrics\Card;
use Illuminate\Support\Facades\Cache;
use Weiaibaicai\OperationLog\Models\OperationLog;

class UserController extends \Dcat\Admin\Http\Controllers\UserController
{
    protected function grid()
    {
        $builder = Administrator::with(['roles', 'departments' => function ($q) {
            $q->select(['id', 'title'])->withPivot('is_manager');
        }])
            ->select(['id', 'username', 'name', 'crm_username', 'created_at', 'updated_at']);
        return Grid::make($builder, function (Grid $grid) {

            $grid->column('id', 'ID')->sortable();
            $grid->column('username');
            $grid->column('name');

            $grid->column('departments', '部门(红色为部长)')->display(function ($val) {
                $str = "";
                foreach ($val as $item) {
                    $isManager = data_get($item, 'pivot.is_manager');
                    $color = $isManager ? '#C06156' : '#586cb1';
                    $str .= "
                        <span class='label' style='background:{$color};'>{$item['title']}</span>
                        ";
                }
                return $str;
            });
            if (config('admin.permission.enable')) {
                $grid->column('roles')->pluck('name')->label('primary', 3);

                $permissionModel = config('admin.database.permissions_model');
                $roleModel = config('admin.database.roles_model');
                $nodes = (new $permissionModel())->allNodes();
                $grid->column('permissions')
                    ->if(function () {
                        return !$this->roles->isEmpty();
                    })
                    ->showTreeInDialog(function (Grid\Displayers\DialogTree $tree) use (&$nodes, $roleModel) {
                        $tree->nodes($nodes);

                        foreach (array_column($this->roles->toArray(), 'slug') as $slug) {
                            if ($roleModel::isAdministrator($slug)) {
                                $tree->checkAll();
                            }
                        }
                    })
                    ->else()
                    ->display('');
            }

            $grid->column('crm_username', 'CRM登录用户名');

            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->quickSearch(['id', 'name', 'username']);

            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->showColumnSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->getKey() == Administrator::DEFAULT_ID) {
                    $actions->disableDelete();
                }
            });
        });
    }


    public function userIndex(Content $content): Content
    {
        return $content
            ->translation($this->translation())
            ->title('咨询管理')
            ->body($this->gridOfUser());
    }


    protected function gridOfUser()
    {
        $builder = Administrator::with(['roles', 'departments' => function ($q) {
            $q->select(['id', 'title'])->withPivot('is_manager');
        }, 'group' => function ($q) {
            $q->select(['id', 'name']);
        }])
            ->select(['id', 'username', 'name', 'crm_username', 'dispatch_limit', 'online', 'order'])
            ->orderBy('order');

        return Grid::make($builder, function (Grid $grid) {
            if (\Admin::user()->can('user.sortable'))
                $grid->sortable();
            $grid->simplePaginate();
            $grid->paginate(100);


            $grid->showColumnSelector();

            if (\Admin::user()->can('user.create')) {
                $grid->enableDialogCreate();
                $grid->disableViewButton();
                $grid->disableEditButton();
                $grid->disableDeleteButton();
                $grid->showQuickEditButton();
            } else {
                $grid->disableCreateButton();
                $grid->disableActions();
            }
            $grid->disableBatchDelete();

//            $grid->disableBatchActions();
            $grid->setResource("auth/users");

            $grid->model()
                ->addQuery('whereHas', ['roles', function ($query) {
                    $query->where('slug', Administrator::DISPATCH_KEY);
                }])
                ->orderBy('order');

            $grid->header(function () use ($grid) {
                $row = new Row();

                $row->column(1 / 3, function (Column $column) use ($grid) {
                    $card = new MyCard("在线人数");
                    $card->appendHtmlAttribute('style', "margin-bottom:0px;margin-top:15px;");


                    $data = Administrator::query()
                        ->select(['id', 'online', 'dispatch_limit'])
                        ->whereHas("roles", function ($query) {
                            $query->where('slug', Administrator::DISPATCH_KEY);
                        })->where('online', 1)
                        ->get();
                    $total = $data->sum("full_dispatch_limit");
                    $todayTotal = $data->sum("today_dispatch_count");

                    $card->content($data->count());
                    $card->footer("所需线索量: $todayTotal / <strong>$total</strong>");
                    $column->row($card);
                });
                return $row;
            });

            if (\Admin::user()->can('user.import'))
                $grid->tools([new ImportUserToolButton()]);

            $grid->column('username', '登录用户名');
            $grid->column('name', '用户名');
            $grid->column('group', '分组')->pluck('name')->label();
            $grid->column('departments', '部门(红色为部长)')->display(function ($val) {
                $str = "";
                foreach ($val as $item) {
                    $isManager = data_get($item, 'pivot.is_manager');
                    $color = $isManager ? '#C06156' : '#586cb1';
                    $str .= "
                        <span class='label' style='background:{$color};'>{$item['title']}</span>
                        ";
                }
                return $str;
            });

            $grid->column('today_dispatch_count', '今天分配数量')
                ->display(function ($val) {
                    return "$val / $this->full_dispatch_limit";
                });

            $grid->column('dispatch_limit', '日分配上限')
                ->editable();
            $grid->column('today_dispatch_limit', '临时增加上限(今天)')
                ->display(function ($val) {
                    return $val;
                })
                ->editable();
            $grid->column('online', '在线状态')
                ->switch();

            $grid->column('pre_dispatch_date', '上次分配时间')->display(function () {
                $date = Cache::get($this->id . Administrator::$dispatchDateKey);
                return $date ? Carbon::parse($date)->toDateTimeString() : '';
            });

            $grid->quickSearch(['id', 'name', 'username']);


            $grid->filter(function (Grid\Filter $filter) {
                $departmentOptions = Department::selectOptions(null, '无部门');
                $filter->where('department', function ($query) {
                    $val = $this->input;
                    if (!$val) {
                        $query->doesntHave("departments");
                    } else {

                        $managerUserId = Department::descendantsAndSelfId(Department::query()
                            ->where('id', $val));
                        $query->whereHas("departments", function ($q) use ($managerUserId) {
                            $q->whereIn('department_id', $managerUserId);
                        });
                    }
                }, '部门')
                    ->select($departmentOptions);
                $groupOptions = UserGroup::query()->select(['id', 'name'])->pluck('name', 'id');
                $filter->where('group_id', function ($query) {
                    if ($this->input) {
                        $query->whereHas('group', function ($q) {
                            $q->where('group_id', $this->input);
                        });
                    }
                }, '分组')->select($groupOptions);
                $filter->equal("online", '在线状态')
                    ->radio([
                        0 => '离线',
                        1 => '在线',
                    ]);
            });
        });
    }


    public function form()
    {
        return Form::make(Administrator::with(['roles', 'departments' => function ($q) {
            $q->withPivot('is_manager')->select(['id']);
        }]), function (Form $form) {
            $userTable = config('admin.database.users_table');

            $connection = config('admin.database.connection');

            $id = $form->getKey();
            $form->hidden('order')->default(0);
            $form->display('id', 'ID');

            $form->text('username', trans('admin.username'))
                ->required()
                ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                ->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
            $form->text('name', trans('admin.name'))->required();
            $form->image('avatar', trans('admin.avatar'))->autoUpload();
            $form->switch('online', 'online')->default(0);
            $form->text('crm_username', 'CRM登录用户名');
            $form->number('dispatch_limit', '日分配上限')
                ->rules('integer|min:0', [
                    'integer' => '必须全部为数字',
                    'min' => '不能小于0',
                ])
                ->default(10);
            if ($id) {
                $form->password('password', trans('admin.password'))
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
            } else {
                $form->password('password', trans('admin.password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
            }

            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->ignore(['password_confirmation']);

            if (config('admin.permission.enable')) {
                $form->multipleSelect('roles', trans('admin.roles'))
                    ->options(function () {
                        $roleModel = config('admin.database.roles_model');
                        $q = $roleModel::query();
                        if (!\Admin::user()->isAdministrator())
                            $q->whereIn('id', [2, 3]);

                        return $q->get()->pluck('name', 'id');
                    })
                    ->customFormat(function ($v) {
                        return array_column($v, 'id');
                    });
            }

            $form->table('departments', '所属部门', function (Form\NestedForm $form) {
                $options = Department::selectOptions(null, null, false);
                $form->select('department_id', '部门')
                    ->options($options)
                    ->required();
                $form->switch('is_manager', '是否为部门管理员');
            })->customFormat(function ($val) {
                return collect($val)->map(function ($item) {
                    return [
                        'department_id' => data_get($item, 'pivot.department_id'),
                        'is_manager' => data_get($item, 'pivot.is_manager'),
                    ];
                });
            })->saving(function ($val) {
                $result = [];
                foreach ($val as $item) {
                    $result[$item['department_id']] = [
                        'is_manager' => data_get($item, 'is_manager', 0)
                    ];
                }
                return $result;
            });

            $form->hidden('today_dispatch_limit')->rules('nullable|integer|min:0',
                [
                    'integer' => '必须全部为数字',
                    'min' => '不能小于0',
                ]);
            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));

            if ($id == Administrator::DEFAULT_ID) {
                $form->disableDeleteButton();
            }
        })->saving(function (Form $form) {
            if (!request()->exists(['_file_', 'upload_column', 'size'])) {
                if ($form->password && $form->model()->get('password') != $form->password) {
                    $form->password = bcrypt($form->password);
                }

                if (!$form->password) {
                    $form->deleteInput('password');
                }
                if(is_numeric($form->input('online'))) {
                    OperationLog::makeLog([
                        '用户ID' => $form->model()->id,
                        '用户' => $form->model()->name,
                        '切换后状态' => $form->input('online') ? '在线' : '离线'
                    ], '管理切换登录状态');
                }

                if ($departments = $form->input('departments')) {
                    $departments = collect($departments)
                        ->filter(function ($item) {
                            return !$item['_remove_'] && $item['department_id'];
                        })
                        ->unique('department_id')
                        ->toArray();
                    $form->input('departments', $departments);
                }
            }
        });
    }

}
